import { SearchBar, List, Toast, Button, Space } from 'antd-mobile'
import React, { useState } from 'react'
import { searchAPI, searchDepartmentAPI } from '../../api/reques'

// 搜索结果的类型定义
interface SearchResult {
  id?: string
  name?: string
  title?: string
  content?: string
  department?: string
  hospital?: string
  // 科室相关字段
  departmentName?: string
  departmentId?: string
  departmentDescription?: string
  departmentType?: string
  // 通用字段
  [key: string]: unknown
}

// 搜索类型
type SearchType = 'general' | 'department'

function Index() {
  const [searchValue, setSearchValue] = useState('')
  const [searchResults, setSearchResults] = useState<SearchResult[]>([])
  const [loading, setLoading] = useState(false)
  const [hasSearched, setHasSearched] = useState(false)
  const [searchType, setSearchType] = useState<SearchType>('general')

  // 搜索函数
  const handleSearch = async (value: string) => {
    // 检查输入是否为空
    if (!value.trim()) {
      Toast.show({
        content: '请输入搜索内容',
        position: 'center',
      })
      return
    }

    setLoading(true)
    setSearchValue(value)
    
    // 打印搜索参数到控制台
    const searchParams = {
      pageCode: 1,
      pageSize: 20,
      searchValue: value.trim(),
      searchType: searchType
    }
    
    console.log('🔍 开始搜索:', searchParams)
    console.log('📝 搜索类型:', searchType === 'department' ? '科室搜索' : '内容搜索')
    console.log('🔑 搜索关键词:', value.trim())
    
    try {
      // 根据搜索类型选择不同的API
      const searchFunction = searchType === 'department' ? searchDepartmentAPI : searchAPI
      console.log('🌐 调用API:', searchType === 'department' ? 'searchDepartmentAPI' : 'searchAPI')
      
      const response = await searchFunction({
        pageCode: 1,
        pageSize: 20,
        searchValue: value.trim()
      })
      
      console.log('✅ 搜索响应成功:', response)
      console.log('📊 响应数据类型:', typeof response)
      console.log('📋 响应是否为数组:', Array.isArray(response))
      
      // 处理搜索结果
      let results: SearchResult[] = []
      if (response && typeof response === 'object') {
        if (Array.isArray(response)) {
          results = response
          console.log('📋 直接数组响应，结果数量:', results.length)
        } else {
          const responseObj = response as Record<string, unknown>
          console.log('🔍 响应对象结构:', Object.keys(responseObj))
          
          if (responseObj.data && Array.isArray(responseObj.data)) {
            results = responseObj.data as SearchResult[]
            console.log('📋 从data字段获取结果，数量:', results.length)
          } else {
            console.log('⚠️ 响应对象中没有找到data数组字段')
          }
        }
      }
      
      console.log('🎯 最终搜索结果:', results)
      console.log('📊 结果数量:', results.length)
      
      // 打印每个结果的详细信息
      if (results.length > 0) {
        console.log('📋 搜索结果详情:')
        results.forEach((item, index) => {
          console.log(`  ${index + 1}. 结果项:`, item)
          console.log(`     - 字段列表:`, Object.keys(item))
          if (item.name) console.log(`     - 名称: ${item.name}`)
          if (item.title) console.log(`     - 标题: ${item.title}`)
          if (item.departmentName) console.log(`     - 科室名称: ${item.departmentName}`)
          if (item.department) console.log(`     - 科室: ${item.department}`)
          if (item.departmentType) console.log(`     - 科室类型: ${item.departmentType}`)
          if (item.departmentDescription) console.log(`     - 科室描述: ${item.departmentDescription}`)
          if (item.hospital) console.log(`     - 医院: ${item.hospital}`)
          if (item.content) console.log(`     - 内容: ${String(item.content).substring(0, 100)}...`)
        })
      }
      
      setSearchResults(results)
      setHasSearched(true)
      
      Toast.show({
        content: `搜索完成，找到 ${results.length} 条结果`,
        position: 'center',
      })
      
    } catch (error) {
      console.error('❌ 搜索失败:', error)
      console.error('🚨 错误详情:', {
        message: error instanceof Error ? error.message : '未知错误',
        stack: error instanceof Error ? error.stack : undefined,
        error: error
      })
      
      setSearchResults([])
      setHasSearched(true)
      
      Toast.show({
        content: '搜索失败，请稍后重试',
        position: 'center',
      })
    } finally {
      setLoading(false)
      console.log('🏁 搜索流程结束，加载状态:', false)
    }
  }

  // 清空搜索
  const handleClear = () => {
    console.log('🧹 清空搜索')
    console.log('📝 清空前的搜索值:', searchValue)
    console.log('📝 清空前的搜索结果数量:', searchResults.length)
    
    setSearchValue('')
    setSearchResults([])
    setHasSearched(false)
    
    console.log('✅ 搜索已清空')
  }

  // 渲染搜索结果
  const renderSearchResults = () => {
    if (!hasSearched) {
      return null
    }

    if (loading) {
      return (
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <div style={{ fontSize: '16px', color: '#666' }}>搜索中...</div>
          <div style={{ fontSize: '14px', color: '#999', marginTop: '8px' }}>
            正在搜索{searchType === 'department' ? '科室' : '内容'}，请稍候
          </div>
        </div>
      )
    }

    if (searchResults.length === 0) {
      return (
        <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
          <div style={{ fontSize: '16px' }}>未找到相关结果</div>
          <div style={{ fontSize: '14px', marginTop: '8px' }}>
            尝试使用其他关键词或切换搜索类型
          </div>
        </div>
      )
    }

    return (
      <div style={{ marginTop: '20px' }}>
        <h3 style={{ margin: '0 0 16px 16px', fontSize: '16px', color: '#333' }}>
          搜索结果 ({searchResults.length}) - {searchType === 'department' ? '科室' : '内容'}
        </h3>
        <List>
          {searchResults.map((item, index) => (
            <List.Item
              key={item.id || index}
              style={{ 
                borderBottom: '1px solid #f0f0f0',
                padding: '12px 16px'
              }}
            >
              <div>
                {/* 科室名称 */}
                {(item.name || item.title || item.departmentName) && (
                  <div style={{ fontWeight: 'bold', marginBottom: '4px', color: '#1890ff' }}>
                    {String(item.name || item.title || item.departmentName)}
                  </div>
                )}
                
                {/* 科室信息 */}
                {(item.department || item.departmentType) && (
                  <div style={{ 
                    color: '#52c41a', 
                    fontSize: '14px',
                    marginBottom: '4px',
                    fontWeight: '500'
                  }}>
                    科室类型: {String(item.department || item.departmentType)}
                  </div>
                )}
                
                {/* 医院信息 */}
                {item.hospital && (
                  <div style={{ 
                    color: '#722ed1', 
                    fontSize: '14px',
                    marginBottom: '4px'
                  }}>
                    医院: {String(item.hospital)}
                  </div>
                )}
                
                {/* 科室描述 */}
                {(item.content || item.departmentDescription) && (
                  <div style={{ 
                    color: '#666', 
                    fontSize: '14px',
                    lineHeight: '1.5'
                  }}>
                    {String(item.content || item.departmentDescription)}
                  </div>
                )}
                {/* 显示其他可能的字段 */}
                {Object.keys(item).map(key => {
                  if (!['id', 'name', 'title', 'content', 'department', 'hospital'].includes(key) && item[key]) {
                    return (
                      <div key={key} style={{ 
                        color: '#999', 
                        fontSize: '12px',
                        marginTop: '4px'
                      }}>
                        {key}: {String(item[key])}
                      </div>
                    )
                  }
                  return null
                })}
              </div>
            </List.Item>
          ))}
        </List>
      </div>
    )
  }

  return (
    <div style={{ padding: '16px' }}>
      {/* 搜索类型切换 */}
      <div style={{ marginBottom: '16px', textAlign: 'center' }}>
        <Space>
          <Button
            size='small'
            color={searchType === 'general' ? 'primary' : 'default'}
            onClick={() => {
              console.log('🔄 切换到内容搜索')
              console.log('📝 切换前搜索类型:', searchType)
              setSearchType('general')
              console.log('✅ 已切换到内容搜索')
              console.log('💡 提示: 内容搜索使用通用搜索接口')
            }}
          >
            内容搜索
          </Button>
          <Button
            size='small'
            color={searchType === 'department' ? 'primary' : 'default'}
            onClick={() => {
              console.log('🔄 切换到科室搜索')
              console.log('📝 切换前搜索类型:', searchType)
              setSearchType('department')
              console.log('✅ 已切换到科室搜索')
            }}
          >
            科室搜索
          </Button>
        </Space>
      </div>

      <SearchBar
        placeholder={`请输入要搜索的${searchType === 'department' ? '科室' : '内容'}`}
        value={searchValue}
        onChange={setSearchValue}
        onSearch={handleSearch}
        onClear={handleClear}
        showCancelButton
        style={{
          marginBottom: '16px',
          backgroundColor: '#f5f5f5',
          borderRadius: '8px'
        }}
      />
      
      {renderSearchResults()}
    </div>
  )
}

export default Index
